package com.senior.english.controller;

import java.sql.SQLException;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.senior.english.config.LoadConfiguration;
import com.senior.english.model.UserModel;
import com.senior.english.servicesImp.UserService;

@Controller
@RequestMapping("login")
public class LoginController {
	UserService userService = (UserService) LoadConfiguration.loadJDBC().getBean("userDAO");
	@RequestMapping(method = RequestMethod.GET)
	public String showForm(ModelMap model) {
		UserModel usermodel = new UserModel();
		model.addAttribute("loginForm", usermodel);
		return "login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processForm(
			@Valid @ModelAttribute("loginForm") UserModel usermodel,
			BindingResult result, ModelMap model) throws SQLException {
		if (result.hasErrors()) {
			return "login";
		}
		if (!userService.checkLogin(usermodel.getUser_name(),usermodel.getPassword())) {
			return "login";
		}
		model.addAttribute("loginForm", usermodel);
		return "loginsuccess";
	}
}
